import requests

import utils

BASE_URL = "https://comtradeplus.un.org"
# API_URL = "/api/Trade/getTrade"
API_URL = "/api/Trade/getCSVDownload" # csv download can access larger data size

BASE_PARAMS = {
    "selectedProductOptionsModified": "C",
    "selectedFrequencyOptionsModified": "A",
    "selectedClassificationOptionsModified": "HS",
    "selectValuePeriodsModified": "2023",
    "selectValueReportersModified": "all",
    "selectValuePartnersModified": "0",
    "selectValueTradeflowsModified": "x,m", # import, export
    "selectValueCommodityCodesModified": "total",
    "selectValueCustomsCodesModified": "c00",
    "selectValueTransportCodesModified": "0",
    "selectValueSecondPartnersModified": "0",
    "selectValueAggregateByModified": "none",
    "selectValueBreakdownModeModified": "plus",
    "selectValueincludeDescModified": "True",
    "selectValuecountOnlyModified": "False"
}

BASE_HEADERS = {
    # "User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0",
    # "Sec-ch-ua-platform": "\"Windows\"",
    # "Referer": "https://comtradeplus.un.org/TradeFlow",
    # "Accept": "application/json, text/plain, */*",
    # "Sec-ch-ua": 'Chromium";v="128", "Not;A=Brand";v="24", "Microsoft Edge";v="128',
    # "Sec-ch-ua-mobile": "?0",
    "Authorization": None
}


def set_additional_request_params(periods=[], reporters=[], partners=[], partner2nds=[], region_ids=None):
    if not region_ids:
        print("no region ids")
        return None
    
    new_periods = []
    try:
        if type(periods) == list:
            new_periods = periods
        elif type(periods) == str:
            if periods[4] == "-":
                start_year = periods[:4]
                end_year = periods[5:9]
                # print(start_year, end_year)
                new_periods = list(range(int(start_year), int(end_year) + 1))
        elif type(periods) == int:
            new_periods = [periods]

    except:
        print("Can't read periods, please check.")
        print("Please write periods with a list like [2012, 2015], or a string like '2012-2015'.")
        exit(4)

    periods_para = ",".join(map(str, new_periods))

    reporters_para = ",".join([str(utils.get_region_id(reporter, region_ids)) for reporter in reporters])

    partners_para = ",".join([str(utils.get_region_id( partner, region_ids)) for partner in partners])

    partners2nds_para = ",".join([str(utils.get_region_id( partner2nd, region_ids)) for partner2nd in partner2nds])

    # print(periods_para, reporters_para, partners_para, partners2nds_para)

    new_request_params = {
        "selectValuePeriodsModified": periods_para,
        "selectValueReportersModified": reporters_para,
        "selectValuePartnersModified": partners_para,
        "selectValueSecondPartnersModified": partners2nds_para
    }
    
    return new_request_params


def request_trade_data(hs_code, additional_params, auth_file="./.auth"):
    url = BASE_URL + API_URL
    headers = BASE_HEADERS
    params = BASE_PARAMS

    if headers["Authorization"] is None or headers["Authorization"] == "":
        # read auth from file.
        # Without auth, the server doesn't response.
        # If you don't have auth code, go to the web, 
        # login your account, and check it from the request headers.
        try:
            auth = utils.read_auth_from_file(auth_file)

        except:
            print("No authorization and can not read from file, please check.")

            exit(1)
        
        headers["Authorization"] = auth

    if additional_params is not None:
        for param in additional_params:
            if param not in params:
                print(f"Useless header: {param}, please check.")
                continue

            params[param] = additional_params[param]

    params["selectValueCommodityCodesModified"] = hs_code

    params_str = ""
    for key in params:
        add_str = key + "=" + str(params[key]) + "&"
        params_str += add_str

    url = url + "?" + params_str[:-1]
    response = requests.get(url, headers=headers)

    # # requests params will use '%2C' to replace ',',
    # # may not accepeted by the server
    # response = requests.get(url, params=params, headers=headers,)
    # print(response.url)

    if response.status_code != 200:
        print("Wrong status code, please check.")
        print(response.headers)
        print(response.text)
        exit(3)

    full_data = None
    try:
        rsp_json = response.json()
        # data_cnt = rsp_json["count"]
        full_data = rsp_json["data"]
        if "error" in rsp_json and rsp_json["error"] != "": 
            print(rsp_json["error"])
            exit(3)
        
    except:
        print(response.text)
        print(response.headers)
        print("The response should be json and contains \"data\", please check.")
        exit(3)

    return full_data


if __name__ == "__main__":

    # url = ""
    # headers = {
    #     "Authorization": ""
    # }
    # res = requests.get(url, headers=headers)
    
    # print(res.url)
    # print(res)

    # print(request_trade_data("total", None))
    pass